package cn.com.api.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.zxing.client.result.BizcardResultParser;

import cn.com.api.entity.ApiDianPing;
import cn.com.api.entity.ApiDingDan;
import cn.com.api.entity.ApiShop;
import cn.com.api.entity.ApiT_city;
import cn.com.api.entity.ApiT_enums;
import cn.com.api.entity.ApiT_shipper_account;
import cn.com.api.entity.ApiT_shipping;
import cn.com.api.entity.ApiT_stats;
import cn.com.api.entity.ApiT_token;
import cn.com.api.entity.ApiTmember;
import cn.com.api.entity.MessageParamData;
import cn.com.api.mapper.ApiDianPingMapper;
import cn.com.api.mapper.ApiDingDanMapper;
import cn.com.api.mapper.ApiShopsMapper;
import cn.com.api.mapper.ApiT_shipper_accountMapper;
import cn.com.api.mapper.ApiT_shippingMapper;
import cn.com.api.mapper.ApiT_statsMapper;
import cn.com.api.mapper.ApiT_tokenMapper;
import cn.com.api.mapper.ApiTmemberMapper;
import cn.com.api.resultpage.InitPushPage;
import cn.com.api.resultpage.MyOrderPage;
import cn.com.api.service.ApiCommonService;
import cn.com.api.service.ApiPushService;
import cn.com.api.service.ApiTOrderMessageService;
import cn.com.api.service.ApiT_cityService;
import cn.com.api.service.ApiT_juan_tjService;
import cn.com.api.service.ApiT_productsService;
import cn.com.api.service.ApiT_shipper_accountService;
import cn.com.api.service.StartOnLoadService;
import cn.com.util.*;

@Service
public class ApiCommonServiceImpl implements ApiCommonService {
	@Autowired
	private ApiTmemberMapper apiTmemberMapper;
	@Autowired
	private ApiShopsMapper apiShopsMapper;
	@Autowired
	private ApiPushService apiPushService;
	@Autowired
	private ApiT_shippingMapper apiT_shippingMapper;
	@Autowired
	private ApiDingDanMapper apiDingDanMapper;
	@Autowired
	private ApiDianPingMapper apiDianPingMapper;
	@Autowired
	private ApiT_shipper_accountMapper apiT_shipper_accountMapper;
	@Autowired
	private ApiT_tokenMapper apiT_tokenMapper;
	@Autowired
	private ApiT_statsMapper apiT_statsMapper;
	@Autowired
	private ApiT_shipper_accountService apiT_shipper_accountService;
	@Autowired
	private ApiT_juan_tjService apiT_juan_tjService;
	@Autowired
	private ApiT_productsService apiT_productsService;
	@Autowired
	private ApiT_cityService apiT_cityService;
	@Autowired
	private ApiTOrderMessageService apiTOrderMessageService;
	@Autowired
	private StartOnLoadService startOnLoadService;

	@Autowired
	// ① 注入上下文
	private ApplicationContext context;

	private ApiCommonService apiCommonServiceSelf;

	private static Logger logger = Logger.getLogger(ApiCommonServiceImpl.class);

	@SuppressWarnings("unused")
	@PostConstruct
	// ③ 初始化方法
	private void setSelf() {
		// 从上下文获取代理对象（如果通过proxtSelf=this是不对的，this是目标对象）
		// 此种方法不适合于prototype Bean，因为每次getBean返回一个新的Bean
		apiCommonServiceSelf = context.getBean(ApiCommonService.class);
	}

	@Override
	public void updateApiTmember(ApiTmember member) {
		String token = Utils.getToken(member.getCuserid());
		member.setToken(token);
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		member.setClogdate(dateFormat.format(now));
		member.setIs_login(1);
		apiTmemberMapper.updateApiTmember(member);
		// 更新token表
		// 根据u_id 和 role 查询token表
		ApiT_token apiTtoken = apiT_tokenMapper.selectApiT_tokenByUidAndRole(member.getCid(), member.getCmtype());
		if (apiTtoken != null) {
			apiTtoken.setToken(token);
			apiTtoken.setOperatedate(DateUtil.nowTimeToString());
			apiT_tokenMapper.updateT_token(apiTtoken);
		} else {
			apiTtoken = new ApiT_token();
			apiTtoken.setUserid(member.getCid().toString());
			apiTtoken.setRole(member.getCmtype());
			apiTtoken.setToken(token);
			apiTtoken.setOperatedate(DateUtil.nowTimeToString());
			apiT_tokenMapper.insertT_token(apiTtoken);
		}
	}

	@Override
	public void updateApiTmemberPass(ApiTmember member) {
		apiTmemberMapper.updateApiTmemberPass(member);

	}

	@Override
	public void setOrderShowStatus(MyOrderPage orderPage) {
		Integer userStatus = 0;
		/** 支付状态 0:已下单未支付 1:已支付 2:已退款 */
		Integer payStatus = orderPage.getPayStatus();
		Integer logisticsStatus = orderPage.getLogisticsStatus();
		Integer shop_id = orderPage.getShop_id();
		String zf_type = orderPage.getPayType();//
		Integer enable = orderPage.getEnable();
		Integer ziying = orderPage.getZiYing();
		Integer orderType = orderPage.getOrderType();

		String takeGoodsTime = orderPage.getTakeGoodsTime();
		Integer return_goods_time = orderPage.getReturn_goods_time();

		if (payStatus != null) {
			// 三大类：正处理-已完成-已取消
			if (2 == enable || 4 == enable) {// 已取消
				userStatus = 6;
			} else if (5 == enable) {// 已完成
				// 查询评价表是否有数据---根据订单号查询
				List<ApiDianPing> dianPingList = apiDianPingMapper.searchDianPingByOrderid(orderPage.getTitles());
				// 判断是否自营
				/** modify by syy start 2016-3-10 自营非自营都允许退货且只能订单完成才能退货 */
				// if(1==ziying){//自营的才有申请退货----判断是否超出分站申请退货时间
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					Date takeGoodsTime_date = dateFormat.parse(takeGoodsTime);
					Date now_date = new Date();
					long duringTime = now_date.getTime() - takeGoodsTime_date.getTime();
					long return_goods_time_long = return_goods_time * 24 * 60 * 60 * 1000;// 数据库配置的时间
					if (duringTime >= return_goods_time_long) {// 收货后持续的时间大于配置的时间--不允许退货
						// 没有退货状态
						if (dianPingList != null && dianPingList.size() > 0) {
							userStatus = 10;// 已完成已评价
						} else {
							userStatus = 9;// 已完成待评价
						}
					} else {
						// 有退货状态
						if (logisticsStatus == 6) {
							if (dianPingList != null && dianPingList.size() > 0) {
								userStatus = 5;// 已完成已评价
							} else {
								userStatus = 4;// 已完成待评价
							}
						} else {// 实际并没有货已送达
								// 没有退货状态
							if (dianPingList != null && dianPingList.size() > 0) {
								userStatus = 10;// 已完成已评价
							} else {
								userStatus = 9;// 已完成待评价
							}
						}

					}
				} catch (ParseException e) {
					e.printStackTrace();
				}

				// }else{
				// if (dianPingList != null && dianPingList.size() > 0) {
				// userStatus = 10;// 已完成已评价
				// } else {
				// userStatus = 9;// 已完成待评价
				// }
				// }

				// 评价需要判断
			} else {// 正处理
				if (0 == payStatus) {// 已下单未支付-------待付款
					/*** 注意货到付款的订单，是什么状态---这里还未判断 **/

					if ("3".equals(zf_type)) {// 货到付款
						/** 订单未完成不能申请退货 syy start 2016-3-10 */
						// if (1 == ziying) {// 自营店
						// if (1 == logisticsStatus) {
						// userStatus = 1;// ---商家待接单
						// } else if(2 == logisticsStatus){
						// userStatus = 2;// ---待发货
						// } else if (3 == logisticsStatus
						// || 4 == logisticsStatus
						// || 5 == logisticsStatus) {
						// userStatus = 3;// ---配送中
						// }
						// } else {// 非自营店
						/** 订单未完成不能申请退货 syy end 2016-3-10 */
						if (1 == logisticsStatus) {
							userStatus = 1;// ---商家待接单
						} else if (2 == logisticsStatus) {
							userStatus = 7;// ---待发货(已接单)--不能申请退货
						} else if (3 == logisticsStatus || 4 == logisticsStatus || 5 == logisticsStatus) {// 已完成的订单
							// 判断是否评价
							userStatus = 8;// 配送中
						}
						// }
					} else {
						userStatus = 0;// 待付款
					}
				} else if (1 == payStatus) {// 已支付
					if (logisticsStatus != null) {
						/**
						 * 订单物流状态 1:商户未确认 2:商户确认接受订单 3:等待配送接单 4:配送确认接受订单
						 * 5:配送取货成功(配送中) 6:用户确认收货 7:退货
						 */
						/**
						 * 判断自营与非自营-------自营-----下单付钱：待发货 非自营---下单付钱：1-待接单 2-待发货
						 */
						// if (1 == ziying) {// 自营商品
						// //3积分兑换-2充值有礼的商品不可退货=====相当于非自营订单
						// if(2==orderType || 3==orderType){
						// if (1 == logisticsStatus) {
						// userStatus = 1;// ---商家待接单
						// } else if (2 == logisticsStatus) {
						// userStatus = 7;// ---待发货(已接单)--不能申请退货
						// } else if (3 == logisticsStatus
						// || 4 == logisticsStatus
						// || 5 == logisticsStatus) {// 已完成的订单
						// // 判断是否评价
						// userStatus = 8;// 配送中
						// } else if (6 == logisticsStatus) {
						// // 判断是否评价------都可申请退货
						// userStatus = 4;// 已完成未评价
						// // userStatus = 5;// 已完成已评价
						// }
						// }else{
						// // 自营商品----有开关，判断是否自动确认接单过程-----订单产生时会判断存储---默认自动接单
						// if (1 == logisticsStatus || 2 == logisticsStatus) {
						// userStatus = 2;// ---待发货
						// } else if (3 == logisticsStatus
						// || 4 == logisticsStatus
						// || 5 == logisticsStatus) {
						// userStatus = 3;// ---配送中
						// } else if (6 == logisticsStatus) {// 已完成的订单
						// // 判断是否评价------都可申请退货
						// userStatus = 4;// 已完成未评价
						// // userStatus = 5;// 已完成已评价
						// } else {
						//
						// }
						// }
						//
						// } else {// 非自营商品
						if (1 == logisticsStatus) {
							userStatus = 1;// ---商家待接单
						} else if (2 == logisticsStatus) {
							userStatus = 7;// ---待发货(已接单)--不能申请退货
						} else if (3 == logisticsStatus || 4 == logisticsStatus || 5 == logisticsStatus) {// 已完成的订单
							// 判断是否评价
							userStatus = 8;// 配送中
						} else if (6 == logisticsStatus) {
							// 判断是否评价------都可申请退货
							userStatus = 4;// 已完成未评价
							// userStatus = 5;// 已完成已评价
						}
						// }
					}
				}
			}

			orderPage.setUserStatus(userStatus);
		}
	}

	/** 判断订单是否需要给商家推送新订单消息 */
	@Override
	public boolean checkNewOrder(String payType, Integer dd_status, Integer zi_status) {
		boolean flag = false;
		if (1 == dd_status) {// 未接单
			// 是否支付
			if (1 == zi_status) {// 已支付
				flag = true;
			} else if (0 == zi_status) {// 未支付
				if ("3".equals(payType)) {
					flag = true;
				}
			}

		}
		return flag;
	}

	/** 提醒配送员配送任务取消 */
	@Override
	public void removeallocateOrder(String u_id, String titles) {
		ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
		InitPushPage pushPage = new InitPushPage();
		pushPage.setDeviceType(member.getDevicetype());
		pushPage.setDeviceId(member.getDeviceid());
		pushPage.setAlert("您好，您的配送任务：" + titles + " 已经取消");
		pushPage.setMessage("您好，您的配送任务：" + titles + " 已经取消");
		pushPage.setTitle("配送任务取消通知！");

		MessageParamData msg = new MessageParamData();
		msg.setCategory(MessageParamData.MSG_CATEGORY_ORDER);
		msg.setSub_category(MessageParamData.MSG_SUB_CATEGORY_ORDER_DELIVER_TOUSER2);
		msg.setOrderId(titles);
		msg.setDesp("This is a new order! Please take this order!!");
		msg.setAlert_action_loc_key("need to play sound");
		msg.setAcme_account("from eddaojia");
		msg.setAcme_message("system msg");
		msg.setAlert_body("hello , have a new order");
		msg.setBadge(1);
		msg.setSound("newOrder.mp3");

		String msgParam = JsonUtil.object2json(msg);
		Map<String, String> params = new HashMap<String, String>();
		params.put("extras", msgParam);
		pushPage.setParams(params);
		apiPushService.sendOrderInfoToSender(pushPage);
	}

	/** 自动+手动分派号配送员时，提醒配送员有新的配送任务 */
	@Override
	public void remindSenderNewTask(String u_id, String titles) {
		ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
		InitPushPage pushPage = new InitPushPage();
		pushPage.setDeviceType(member.getDevicetype());
		pushPage.setDeviceId(member.getDeviceid());
		pushPage.setAlert("您好，有新的配送任务：" + titles);
		pushPage.setMessage("您好，有新的配送任务：" + titles);
		pushPage.setTitle("新的配送任务！");

		MessageParamData msg = new MessageParamData();
		msg.setCategory(MessageParamData.MSG_CATEGORY_ORDER);
		msg.setSub_category(MessageParamData.MSG_SUB_CATEGORY_ORDER_DELIVER_NEWTOSENDER);
		msg.setOrderId(titles);
		msg.setDesp("This is a new order! Please take this order!!");
		msg.setAlert_action_loc_key("need to play sound");
		msg.setAcme_account("from eddaojia");
		msg.setAcme_message("system msg");
		msg.setAlert_body("hello , have a new order");
		msg.setBadge(1);
		msg.setSound("newOrder.mp3");

		String msgParam = JsonUtil.object2json(msg);
		Map<String, String> params = new HashMap<String, String>();
		params.put("extras", msgParam);
		System.out.println("msgParam:---------------------------啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊：" + msgParam);
		pushPage.setParams(params);
		apiPushService.sendOrderInfoToSender(pushPage);
	}

	/**
	 * 产生新的订单时给商家发送消息，订单号发送给商家
	 * 
	 * @param shop_id
	 * @param titles
	 */
	@Override
	public void sendNewOrdersInfoToShop(Integer shop_id, String titles) {
		// 根据shop_id 查询商家的设备类型，设备Id
		ApiShop shop = apiShopsMapper.findT_shopsById(shop_id);
		InitPushPage pushPage = new InitPushPage();
		pushPage.setDeviceType(shop.getDevicetype());
		pushPage.setDeviceId(shop.getDeviceid());
		pushPage.setAlert("您好，有新的订单：" + titles);
		pushPage.setMessage("您好，有新的订单：" + titles);
		pushPage.setTitle("新订单！");

		MessageParamData msg = new MessageParamData();
		msg.setCategory(MessageParamData.MSG_CATEGORY_ORDER);
		msg.setSub_category(MessageParamData.MSG_SUB_CATEGORY_ORDER_SHOP_NEW);
		msg.setOrderId(titles);
		msg.setDesp("This is a new order! Please take this order!!");
		msg.setAlert_action_loc_key("need to play sound");
		msg.setAcme_account("from eddaojia");
		msg.setAcme_message("system msg");
		msg.setAlert_body("hello , have a new order");
		msg.setBadge(1);
		msg.setSound("newOrder.mp3");

		String msgParam = JsonUtil.object2json(msg);
		Map<String, String> params = new HashMap<String, String>();
		params.put("extras", msgParam);
		pushPage.setParams(params);
		apiPushService.sendOrderInfoToShop(pushPage);
	}

	/**
	 * 提醒商家接单
	 * 
	 * @param shop_id
	 * @param titles
	 */
	@Override
	public void remindShopToTakeOrder(Integer shop_id, String titles) {
		// 根据shop_id 查询商家的设备类型，设备Id
		ApiShop shop = apiShopsMapper.findT_shopsById(shop_id);
		InitPushPage pushPage = new InitPushPage();
		pushPage.setDeviceType(shop.getDevicetype());
		pushPage.setDeviceId(shop.getDeviceid());
		pushPage.setAlert("您好，客户提醒接单：" + titles);
		pushPage.setMessage("您好，客户提醒接单：" + titles);
		pushPage.setTitle("提醒接单！");

		MessageParamData msg = new MessageParamData();
		msg.setCategory(MessageParamData.MSG_CATEGORY_ORDER);
		msg.setSub_category(MessageParamData.MSG_SUB_CATEGORY_ORDER_SHOP_REMINDTAKE);
		msg.setOrderId(titles);
		msg.setDesp("This is a new order! Please take this order!!");
		msg.setAlert_action_loc_key("need to play sound");
		msg.setAcme_account("from eddaojia");
		msg.setAcme_message("system msg");
		msg.setAlert_body("hello , have a new order");
		msg.setBadge(1);
		msg.setSound("newOrder.mp3");

		String msgParam = JsonUtil.object2json(msg);
		Map<String, String> params = new HashMap<String, String>();
		params.put("extras", msgParam);
		pushPage.setParams(params);
		apiPushService.sendOrderInfoToShop(pushPage);
	}

	/**
	 * 提醒商家发货
	 * 
	 * @param shop_id
	 * @param titles
	 */
	@Override
	public void remindShopToSendGoods(Integer shop_id, String titles) {
		ApiShop shop = apiShopsMapper.findT_shopsById(shop_id);
		InitPushPage pushPage = new InitPushPage();
		pushPage.setDeviceType(shop.getDevicetype());
		pushPage.setDeviceId(shop.getDeviceid());
		pushPage.setAlert("您好，客户提醒发货：" + titles);
		pushPage.setMessage("您好，客户提醒发货：" + titles);
		pushPage.setTitle("提醒发货！");

		MessageParamData msg = new MessageParamData();
		msg.setCategory(MessageParamData.MSG_CATEGORY_ORDER);
		msg.setSub_category(MessageParamData.MSG_SUB_CATEGORY_ORDER_SHOP_REMINDSEND);
		msg.setOrderId(titles);
		msg.setDesp("This is a new order! Please take this order!!");
		msg.setAlert_action_loc_key("need to play sound");
		msg.setAcme_account("from eddaojia");
		msg.setAcme_message("system msg");
		msg.setAlert_body("hello , have a new order");
		msg.setBadge(1);
		msg.setSound("newOrder.mp3");

		String msgParam = JsonUtil.object2json(msg);
		Map<String, String> params = new HashMap<String, String>();
		params.put("extras", msgParam);
		pushPage.setParams(params);
		apiPushService.sendOrderInfoToShop(pushPage);
	}

	@Override
	public void allocateOrderTask(String orderId) {
		try {
			/**
			 * autoallocateorder---从数据库查询是否自动派单---可关闭自动派单全部改为手动派单
			 * 从配送员表里查询在岗，任务已全部货已送达的配送员----空载的配送员 订单要求的配送时间----配送的收货地址--不考虑在这 1-
			 * 2-先查询商铺city_id=配送员的city_id 配送员空闲
			 */
			// 根据订单号查询店铺 shop_id city_id 店铺的经纬度
			ApiShop shop = apiShopsMapper.getShopByOrderId(orderId);
			// 该站点是否自动派单--is_auto_allocateorder same_distance
			ApiT_city city = apiT_cityService.findT_cityById(shop.getC_city_id());
			if (1 == city.getIs_auto_allocateorder()) {// 自动派单
				List<ApiT_token> userList = new ArrayList<ApiT_token>();
				System.out.println("给订单分派配送员-订单号：" + orderId + "-店铺：" + shop + "-店铺名：" + shop.getcSname());
				userList = apiT_shipper_accountMapper.selectMemebrNoTask(shop.getC_city_id());
				String shopLongitude = shop.getLongitude().toString();
				String shopLatitude = shop.getLatitude().toString();
				System.out.println("订单：" + orderId + "查询到的配送员个数：" + userList.size());
				if (userList != null && userList.size() > 0) {
					// 多个配送员，每次取距离小的
					String user_id = "";
					BigDecimal distance = new BigDecimal(0.0);
					Integer receiveOrderCount = 0;
					System.out.println("在岗空闲的配送员：");
					for (ApiT_token user : userList) {
						System.out.println("-------------------------查询到的同一个city_id 的配送员：" + user.getUserid());
						if (Util.isNull(user_id)) {// 第一次赋值
							user_id = user.getUserid();
							distance = new BigDecimal(Utils.GetDistance(shopLatitude, shopLongitude, user.getLatitude(),
									user.getLongitude()));
						} else {
							BigDecimal distanceTemp = new BigDecimal(Utils.GetDistance(shopLatitude, shopLongitude,
									user.getLatitude(), user.getLongitude()));
							if (distance.compareTo(distanceTemp) > 0) {// 大于的话，替换
								user_id = user.getUserid();
								distance = distanceTemp;
							}
						}
					}
					logger.info("派单-订单" + orderId + "到店铺最近的配送员距离：" + distance);
					// 最小距离+数据库配置的距离算是在 相同距离内---所有这些人算当日接单最少的
					Double same_distance = distance.doubleValue() + city.getSame_distance();
					// 遍历所有在这个距离内，接单最少的配送员
					user_id = "";
					for (ApiT_token user : userList) {
						if (user.getTo_shop_distance() < same_distance) {
							if (Util.isNull(user_id)) {
								user_id = user.getUserid();
								receiveOrderCount = user.getToday_receive_order_count();
							} else {
								if (user.getToday_receive_order_count() < receiveOrderCount) {
									user_id = user.getUserid();
									receiveOrderCount = user.getToday_receive_order_count();
								}
							}
						}
					}
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("orderId", orderId);
					map.put("user_id", user_id);
					apiT_shippingMapper.updateT_shippingByOrderId(map);
					apiDingDanMapper.updateDingDanDdstatusByOrderId(map);
					/** 任务分派后，提醒配送员有新的配送任务 */
					apiTOrderMessageService.remindSenderNewTask(user_id, orderId);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}

	}

	/** 定时任务-自动分派配送员 */
	@Override
	public void autoAllocateTask() {
		try {
			// 直接查询出需要自动分派配送员的订单
			List<ApiT_shipping> shippingList = apiT_shippingMapper.searchT_shippingNoAllocate();// 未分派配送员的订单
			if (shippingList != null && shippingList.size() > 0) {
				for (ApiT_shipping shipping : shippingList) {// 每一个订单，判断city_id
																// 距离-到商家分配配送员
					String orderId = shipping.getOrder_id();
					// 根据订单号查询店铺 shop_id city_id 店铺的经纬度
					ApiShop shop = apiShopsMapper.getShopByOrderId(orderId);
					List<ApiT_token> userList = new ArrayList<ApiT_token>();
					userList = apiT_shipper_accountMapper.selectMemebrNoTask(shop.getC_city_id());
					String shopLongitude = shop.getLongitude().toString();
					String shopLatitude = shop.getLatitude().toString();
					if (userList != null && userList.size() > 0) {
						// 多个配送员，每次取距离小的
						String user_id = "";
						BigDecimal distance = new BigDecimal(0.0);
						Integer receiveOrderCount = 0;
						System.out.println("在岗空闲的配送员：");
						for (ApiT_token user : userList) {
							System.out.println("-------------------------查询到的同一个city_id 的配送员：" + user.getUserid());
							if (Util.isNull(user_id)) {// 第一次赋值
								user_id = user.getUserid();
								distance = new BigDecimal(Utils.GetDistance(shopLatitude, shopLongitude,
										user.getLatitude(), user.getLongitude()));
								user.setTo_shop_distance(distance.doubleValue());
							} else {
								BigDecimal distanceTemp = new BigDecimal(Utils.GetDistance(shopLatitude, shopLongitude,
										user.getLatitude(), user.getLongitude()));
								if (distance.compareTo(distanceTemp) > 0) {// 大于的话，替换
									user_id = user.getUserid();
									distance = distanceTemp;
								}
								user.setTo_shop_distance(distanceTemp.doubleValue());
							}
						}
						// 最小距离+数据库配置的距离算是在 相同距离内---所有这些人算当日接单最少的
						Double same_distance = distance.doubleValue() + shipping.getSame_distance();
						// 遍历所有在这个距离内，接单最少的配送员
						user_id = "";
						for (ApiT_token user : userList) {
							if (user.getTo_shop_distance() < same_distance) {
								if (Util.isNull(user_id)) {
									user_id = user.getUserid();
									receiveOrderCount = user.getToday_receive_order_count();
								} else {
									if (user.getToday_receive_order_count() < receiveOrderCount) {
										user_id = user.getUserid();
										receiveOrderCount = user.getToday_receive_order_count();
									}
								}
							}
						}

						Map<String, Object> map = new HashMap<String, Object>();
						map.put("orderId", orderId);
						map.put("user_id", user_id);
						apiT_shippingMapper.updateT_shippingByOrderId(map);
						apiDingDanMapper.updateDingDanDdstatusByOrderId(map);
						/** 任务分派后，提醒配送员有新的配送任务 */
						apiTOrderMessageService.remindSenderNewTask(user_id, orderId);
					}
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
	}

	@Override
	public void remindUserOrderInSending(String u_id, String titles) {
		ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
		InitPushPage pushPage = new InitPushPage();
		pushPage.setDeviceType(member.getDevicetype());
		pushPage.setDeviceId(member.getDeviceid());
		pushPage.setAlert("您好，您的订单：" + titles + "已在配送途中，请时刻关注！");
		pushPage.setMessage("您好，您的订单：" + titles + "已在配送途中，请时刻关注！");
		pushPage.setTitle("订单配送中！");

		MessageParamData msg = new MessageParamData();
		msg.setCategory(MessageParamData.MSG_CATEGORY_ORDER);
		msg.setSub_category(MessageParamData.MSG_SUB_CATEGORY_ORDER_USER_SENDING);
		msg.setOrderId(titles);
		msg.setDesp("This is a new order! Please take this order!!");
		msg.setAlert_action_loc_key("need to play sound");
		msg.setAcme_account("from eddaojia");
		msg.setAcme_message("system msg");
		msg.setAlert_body("hello , have a new order");
		msg.setBadge(1);
		msg.setSound("newOrder.mp3");

		String msgParam = JsonUtil.object2json(msg);
		Map<String, String> params = new HashMap<String, String>();
		params.put("extras", msgParam);
		pushPage.setParams(params);
		apiPushService.sendOrderInfoToUser(pushPage);
	}

	// 货已送达，提醒客户对本次配送服务进行评价
	@Override
	public void remindUserEvaluate(String u_id, String titles) {
		ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
		InitPushPage pushPage = new InitPushPage();
		pushPage.setDeviceType(member.getDevicetype());
		pushPage.setDeviceId(member.getDeviceid());
		pushPage.setAlert("亲爱的客户您好，您的订单：" + titles + "已送达，请对本次配送服务评价！");
		pushPage.setMessage("亲爱的客户您好，您的订单：" + titles + "已送达，请对本次配送服务评价！");
		pushPage.setTitle("订单已送达！");
		MessageParamData msg = new MessageParamData();
		msg.setCategory(MessageParamData.MSG_CATEGORY_ORDER);
		msg.setSub_category(MessageParamData.MSG_SUB_CATEGORY_ORDER_USER_RECEIVE);
		msg.setOrderId(titles);
		msg.setDesp("This is a received order! Please evaluate!");
		msg.setAlert_action_loc_key("need to play sound");
		msg.setAcme_account("from eddaojia");
		msg.setAcme_message("system msg");
		msg.setAlert_body("hello , order have received");
		msg.setBadge(1);
		msg.setSound("newOrder.mp3");

		String msgParam = JsonUtil.object2json(msg);
		Map<String, String> params = new HashMap<String, String>();
		params.put("extras", msgParam);
		pushPage.setParams(params);
		apiPushService.sendOrderInfoToUser(pushPage);
	}

	/**
	 * 订单下单1小时后，若未付款，则超时取消订单 目前先改为：1天未支付
	 */
	@Transactional
	@Override
	public void cancelOverTimeOrders() {
		/** 查询enable1-已下单，zi_status=0&&zf_type!=3 未支付的订单 */
		List<ApiDingDan> dingDanList = apiDingDanMapper.searchNewOrdersNotPay();

		/** 将这些订单改为取消 */
		if (dingDanList != null && dingDanList.size() > 0) {
			List<String> list = new ArrayList<String>();
			for (ApiDingDan dingDan : dingDanList) {
				list.add(dingDan.getTitles());
				System.out.println("自动取消的订单号：" + dingDan.getTitles());
				logger.info("自动取消的订单号：" + dingDan.getTitles());
			}

			apiDingDanMapper.updateCancelOrdersTask(list);
			for (ApiDingDan dingDan : dingDanList) {
				// 判断是否使用优惠券，恢复其使用
				apiT_juan_tjService.recoveryJuanOnDingDan(dingDan);
				// 恢复库存数量
				apiT_productsService.modifyProductCountByOrderId(dingDan.getTitles());
			}
		}
	}

	/** 设置已完成订单的配送评价-默认4星评价 */
	@Override
	@Transactional
	public void setupCompleteOrderRemark() {
		apiT_shippingMapper.updateShippingRemarkNoEvaluate();
	}

	@Override
	@Transactional
	public void allocateOrderTaskManually(String orderId, String shipper_user_id) {
		try {
			/**
			 * 查询到的配送员
			 */
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("orderId", orderId);
			map.put("user_id", shipper_user_id);
			apiT_shippingMapper.updateT_shippingByOrderId(map);
			apiDingDanMapper.updateDingDanDdstatusByOrderId(map);

			/** 任务分派后，提醒配送员有新的配送任务 */
			apiTOrderMessageService.remindSenderNewTask(shipper_user_id, orderId);

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}

	}

	@Override
	@Transactional
	public void shipperKPIcomputing(Date theDate) {
		// TODO
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(theDate);
		String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());

		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int hour = calendar.get(Calendar.HOUR_OF_DAY); // --这个不用

		ApiT_stats stats = new ApiT_stats();
		/**
		 * 店铺、配送员、订单数量 订单总金额 准时数量 超时数量 早达数量----基本条件：货已送达 查询昨日的---每晚24:00前执行
		 * 即当天的记录数---否则calendar 要重新赋值 1-查当天货已送达的 2-按配送员 sendlist 3-按店铺 shoplist
		 */
		System.out.println("nowDate:" + nowDate);
		List<ApiT_shipping> shippingList = apiT_shippingMapper.searchTodayFinishTask2(nowDate);

		if (shippingList != null && shippingList.size() > 0) {
			System.out.println("-----shippingList有值");
			// 1-按配送员
			Map<String, List<ApiT_shipping>> sendMap = new HashMap<String, List<ApiT_shipping>>();
			// 2-按店铺
			Map<Integer, List<ApiT_shipping>> shopMap = new HashMap<Integer, List<ApiT_shipping>>();
			for (ApiT_shipping ship : shippingList) {
				String u_id = ship.getUser_id();// 配送员
				Integer shop_id = ship.getShop_id();
				if (sendMap.containsKey(u_id)) {// 判断配送员
					sendMap.get(u_id).add(ship);
				} else {
					List<ApiT_shipping> sendList = new ArrayList<ApiT_shipping>();
					sendList.add(ship);
					sendMap.put(u_id, sendList);
				}

				if (shopMap.containsKey(shop_id)) {
					shopMap.get(shop_id).add(ship);
				} else {
					List<ApiT_shipping> shopList = new ArrayList<ApiT_shipping>();
					shopList.add(ship);
					shopMap.put(shop_id, shopList);
				}

			}

			// 插入前先删除当天的，插入最新的 --根据 year month day
			// apiT_statsMapper.deleteDataByTime(year, month, day);
			// change by @RuanCong 2016/02/02
			// 如果这个时间段的统计已经有了，就不再生成记录(不然商家余额会增加多次)
			int count = apiT_statsMapper.getDateByTime(year, month, day);
			if (count > 0) {
				return;
			}

			// 插入统计表
			for (Entry<Integer, List<ApiT_shipping>> entry : shopMap.entrySet()) {
				Integer shop_id = entry.getKey();
				List<ApiT_shipping> shipList = entry.getValue();
				// 遍历获取金额 订单总数量
				BigDecimal sumMoney = BigDecimal.ZERO;
				BigDecimal sendfee = BigDecimal.ZERO;
				BigDecimal sum_lunchbox_price = BigDecimal.ZERO;// 订单中总的餐盒费
				BigDecimal sum_final_pay_money = BigDecimal.ZERO;// 当日要付给商家的最后的钱总数
				Integer orderCount = shipList.size();
				for (ApiT_shipping s : shipList) {
					System.out.println(s.getMoney() + ">>>>>>>>>>");
					sumMoney = sumMoney.add(s.getMoney());
					sendfee = sendfee.add(s.getShipping_price());
					sum_lunchbox_price = sum_lunchbox_price.add(s.getSum_lunchbox_price());
				}
				// 增加可提现金额
				DecimalFormat df = new DecimalFormat("######0.00");
				Map<String, Object> shop = new HashMap<String, Object>();
				shop = apiShopsMapper.findShopByShopId(shop_id + "");
				String settleType = shop.get("balance").toString();// 商家结算方式
				int is_recieve_box_money = (Integer) shop.get("is_recieve_box_money");// 当日餐盒费是否结算给商家
				BigDecimal discount = Util.getBigDecimal(shop.get("discount").toString());
				BigDecimal prePayment = Util.getBigDecimal(shop.get("pre_payment").toString());
				Double cashMoney = Double.parseDouble(shop.get("cash_money") + "");
				Double balance = 0.00;
				if (discount.compareTo(BigDecimal.ZERO) == 1 && !"现结".equals(settleType)) {// 现结不需要统计它的余额
					BigDecimal money = BigDecimal.ZERO;
					if (is_recieve_box_money == 1) {// 1：商家收餐盒费;
						// money =
						// Double.parseDouble(df.format((sumMoney-sendfee) *
						// discount));//商铺所得金额
						money = (sumMoney.subtract(sendfee)).multiply(discount);
					} else if (is_recieve_box_money == 2) {// 2：平台收餐盒费
						// money =
						// Double.parseDouble(df.format((sumMoney-sendfee-sum_lunchbox_price)
						// * discount));//商铺所得金额
						money = (sumMoney.subtract(sendfee).subtract(sum_lunchbox_price)).multiply(discount);
					} else {
						// money =
						// Double.parseDouble(df.format((sumMoney-sendfee) *
						// discount));//商铺所得金额
						money = (sumMoney.subtract(sendfee)).multiply(discount);
					}
					sum_final_pay_money = money;
					if (prePayment.compareTo(BigDecimal.ZERO) == 1) {// 减少预付金
						if (prePayment.compareTo(money) == 1) {// 预付金额充足
							balance = cashMoney;
							apiShopsMapper.updateCashPre(balance, prePayment.subtract(money).doubleValue(), shop_id);
						} else {
							apiShopsMapper.updateCashPre(balance, 0.0, shop_id);// 减掉所有的预付款
							double subMoney = prePayment.subtract(money).doubleValue();// 其它的加入余额
							balance = ArithUtil.add(cashMoney, subMoney);
							apiShopsMapper.updateCashPre(balance, prePayment.doubleValue(), shop_id);
						}
					} else {// 增加提现
						balance = Util.getBigDecimal(cashMoney.toString()).add(money).doubleValue();
						apiShopsMapper.updateCashPre(balance, prePayment.doubleValue(), shop_id);
					}
				}
				Date date = new Date();
				ApiT_stats status = new ApiT_stats();
				status.setShop_id(shop_id);
				status.setOrders_money(sumMoney.doubleValue());
				status.setOrder_count(orderCount);
				status.setYear(year);
				status.setMonth(month);
				status.setDay(day);
				status.setWeek(weekOfYear);
				status.setCreateTime(date);
				status.setBalance(balance);
				status.setSendfee(sendfee.doubleValue());
				status.setSettle_type(settleType);
				status.setDiscount(discount.doubleValue());
				status.setFinal_pay_money(sum_final_pay_money.doubleValue());
				status.setIs_recieve_box_money(is_recieve_box_money);
				status.setSum_lunchbox_price(sum_lunchbox_price.doubleValue());
				apiT_statsMapper.insertT_stats(status);
			}
			for (Entry<String, List<ApiT_shipping>> entry : sendMap.entrySet()) {
				String u_id = entry.getKey();
				ApiT_shipper_account shipperAccount = apiT_shipper_accountMapper.selectShipperAccountByUid(u_id);
				List<ApiT_shipping> shipList = entry.getValue();
				// 遍历获取金额 0准时数量 1超时数量 2早达时间
				Double sumMoney = 0.0;
				Integer orderCount = shipList.size();
				Integer onTimeCount = 0;
				Integer overTimeCount = 0;
				Integer aheadTimeCount = 0;
				BigDecimal on_delivery_money = BigDecimal.ZERO;
				BigDecimal cash_term_money = BigDecimal.ZERO;
				BigDecimal reserve_money = shipperAccount.getReserve_money();
				BigDecimal money = shipperAccount.getMoney();
				for (ApiT_shipping s : shipList) {
					sumMoney = Util.getBigDecimal(sumMoney.toString()).add(s.getMoney()).doubleValue();
					Integer isOnTime = s.getIs_ontime();
					BigDecimal on_delivery_money_one = s.getOn_delivery_money();
					BigDecimal cash_term_money_one = s.getCash_term_money();
					if (on_delivery_money_one != null) {// 累加总的货到付款的钱
						on_delivery_money = on_delivery_money.add(on_delivery_money_one);
					}
					if (cash_term_money_one != null) {// 累加付给商家的钱
						cash_term_money = cash_term_money.add(cash_term_money);
					}
					if (!Util.isNull(isOnTime)) {
						if (0 == isOnTime) {
							onTimeCount = onTimeCount + 1;
						}
						if (1 == isOnTime) {
							overTimeCount = overTimeCount + 1;
						}
						if (2 == isOnTime) {
							aheadTimeCount = aheadTimeCount + 1;
						}
					}
				}
				ApiT_stats status = new ApiT_stats();
				Date date = new Date();
				status.setCreateTime(date);
				status.setShipper_id(u_id);
				status.setOrders_money(sumMoney);
				status.setOrder_count(orderCount);
				status.setOrder_ontime_count(onTimeCount);
				status.setOrder_overtime_count(overTimeCount);
				status.setOrder_aheadtime_count(aheadTimeCount);
				status.setYear(year);
				status.setMonth(month);
				status.setDay(day);
				status.setWeek(weekOfYear);
				status.setOn_delivery_money(on_delivery_money);
				status.setCash_term_money(cash_term_money);
				status.setReserve_money(reserve_money);
				status.setMoney(money);
				apiT_statsMapper.insertT_stats(status);
			}
		}

	}

	@Override
	@Transactional
	// 更改派单
	public void changeallocateOrder(int id, String orderId, String shipper_user_id) {

		try {

			/**
			 * 查询到的配送员
			 */
			ApiT_shipping shipping = apiT_shippingMapper.findT_shippingById(id);
			String before_user_id = shipping.getUser_id();

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("orderId", orderId);
			map.put("user_id", shipper_user_id);
			apiT_shippingMapper.updateT_shippingByOrderId(map);
			apiDingDanMapper.updateDingDanDdstatusByOrderId(map);

			/** 提醒配送员配送任务取消 */
			removeallocateOrder(before_user_id, orderId);
			/** 任务分派后，提醒配送员有新的配送任务 */
			remindSenderNewTask(shipper_user_id, orderId);

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
	}

	@Override
	@Transactional
	public int countUpMonthShipping(int year, int month) {
		int result = 0;
		try {
			int count = apiT_statsMapper.getMonthDataByTime(year, month);
			if (count > 0) {// 如果>0说明当月的数据已经统计过
				return 0;
			}
			result = apiT_statsMapper.countUpMonthShipping(year, month);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return result;
	}

	@Override
	@Transactional
	public int countUpShopMonthShipping(int year, int month) {
		int result = 0;
		try {
			result = apiT_statsMapper.countUpShopMonthShipping(year, month);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return result;
	}

	@Override
	@Transactional
	public int countUpShopWeekShipping(Date date) {
		int result = 0;
		try {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
			if (dayOfWeek != 2) {// 当前日期是不是周一
				return -1;
			}
			String someDay = new SimpleDateFormat("yyyy-MM-dd").format(date);
			result = apiT_statsMapper.countUpShopWeekShipping(someDay);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return result;
	}

	@Override
	@Transactional
	public int dayStationStat(Date nowDate) {
		int result = 0;
		try {
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(nowDate);
			int year = calendar.get(Calendar.YEAR);
			int month = calendar.get(Calendar.MONTH) + 1;
			int day = calendar.get(Calendar.DAY_OF_MONTH);

			result = apiT_statsMapper.dayStationStat(year, month, day);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return result;
	}

	/**
	 * 提醒配送员取衣服
	 * 
	 * @param orderId
	 */
	@Override
	public void remindSenderForClothes(String u_id, String orderId, String message, Integer messageType) {
		ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
		InitPushPage pushPage = new InitPushPage();
		pushPage.setDeviceType(member.getDevicetype());
		pushPage.setDeviceId(member.getDeviceid());
		pushPage.setAlert(message);
		pushPage.setMessage(message);
		pushPage.setTitle("新的配送任务！");

		MessageParamData msg = new MessageParamData();
		msg.setCategory(MessageParamData.MSG_CATEGORY_ORDER);
		if (messageType == 7) {
			msg.setSub_category(MessageParamData.MSG_SUB_CATEGORY_ORDER_DELIVER_TOUSER);
		} else {
			msg.setSub_category(MessageParamData.MSG_SUB_CATEGORY_ORDER_DELIVER_TOSHOP);
		}

		msg.setOrderId(orderId);
		msg.setDesp("This is a new order! Please take this order!!");
		msg.setAlert_action_loc_key("need to play sound");
		msg.setAcme_account("from eddaojia");
		msg.setAcme_message("system msg");
		msg.setAlert_body("hello , have a new order");
		msg.setBadge(1);
		msg.setSound("newOrder.mp3");

		String msgParam = JsonUtil.object2json(msg);
		Map<String, String> params = new HashMap<String, String>();
		params.put("extras", msgParam);
		System.out.println("msgParam:---------------------------啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊：" + msgParam);
		pushPage.setParams(params);
		apiPushService.sendOrderInfoToSender(pushPage);
	}

	/**
	 * enum_dict_get 数据字典中获取数据集
	 * 
	 * @param key
	 *            数据字段索引
	 */
	public List<ApiT_enums> enum_dict_get(String key) {
		// 文章类型 从数据字典中去
		List<ApiT_enums> dict = new ArrayList<ApiT_enums>();
		// List<ApiT_enums> _enums = apiT_enumsMapper.findT_enumss();
		List<ApiT_enums> enums = startOnLoadService.enum_dict();
		String enum_id = "0";
		for (ApiT_enums the_enum : enums) {
			if (the_enum.getItem_key().equalsIgnoreCase(key))
				enum_id = the_enum.getId() + "";
		}
		for (ApiT_enums the_enum : enums) {
			if (the_enum.getParent_id().equalsIgnoreCase(enum_id))
				dict.add(the_enum);
		}
		//
		return dict;
	}

}
